package com.tanhua.app.service;

import com.tanhua.api.service.UserApi;
import com.tanhua.app.Interceptor.UserHolder;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.HuanXinUserVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserApi userApi;

    // 通用数据
    private final String CHECK_CODE = "CHECK_CODE_";

    /**
     * 发送验证码
     */
    public void sendCode(String mobile) {
/*        // 1. 生成随机数
        String code = RandomStringUtils.randomNumeric(6);

        // 2. 发送验证码
        try {
            smsTemplate.send(mobile, code);
        } catch (Exception e) {
            // 发送验证码失败，抛出异常
            throw new BusinessException(ErrorResult.fail());
        }*/

        String code = "123456";

        // 3. 缓存验证码
        redisTemplate.opsForValue().set(CHECK_CODE + mobile, code, Duration.ofMinutes(5));
    }

    /**
     * 用户登陆
     * @param mobile
     * @param code
     * @return
     */
    public Map loginVerification(String mobile, String code) {
        // 1. 从Redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(CHECK_CODE + mobile);

        // 2. 校验验证码是否失效
        if (StringUtils.isEmpty(redisCode)) {
            throw new BusinessException(ErrorResult.loginError());
        }

        // 3. 校验验证码
        if (!redisCode.equals(code)) {
            throw new BusinessException(ErrorResult.checkLoginError());
        }

        // 校验成功删除，Redis中的验证码
        redisTemplate.delete(CHECK_CODE + mobile);

        // 假设用户已经注册
        boolean isNew = false;

        // 4. 检测手机号是否组测
        User user = userApi.findByMobile(mobile);
        if (user == null) {
            // 未注册，需要注册
            user = new User();
            user.setMobile(mobile);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            user.setId(id);

            // 添加环信的用户和密码
            String hxUserName = Constants.HX_USER_PREFIX + user.getId();
            String hxPassword = Constants.INIT_PASSWORD;

            Boolean flagUser = huanXinTemplate.createUser(hxUserName, hxPassword);

            if (flagUser) {
                user.setHxUser(hxUserName);
                user.setHxPassword(hxPassword);
                userApi.update(user);
            }

            isNew = true;
        }

        // 5. 登陆成功，生成token
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile", user.getMobile());
        String token = JwtUtils.getToken(tokenMap);

        // 6. 分装数据返回
        Map<String,Object> retMap = new HashMap<>();
        retMap.put("token",token);
        retMap.put("isNew",isNew);

        return retMap;
    }

    /**
     * 查询环信信息
     * @return
     */
    public HuanXinUserVo findHuanXin() {

        // 获取当前用户id
        Long userId = UserHolder.getUserId();

        // 根据用户id查询用户数据
        User user = userApi.findByUserId(userId);

        if (user == null) {
            throw new BusinessException(ErrorResult.HuanXinError());
        }

        return new HuanXinUserVo(user.getHxUser(),user.getHxPassword());

    }
}
